<template>
  <PageWrapper>
    <a-form
      name="basic"
      :model="insideData.data"
      scrollToFirstError
      :label-col="{
        xs: { span: 5 },
        sm: { span: 6 },
        md: { span: 8 },
        lg: { span: 8 },
        xl: { span: 7 },
        xxl: { span: 7 },
      }"
      :wrapper-col="{
        xs: { span: 15 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: 10 },
        xl: { span: 7 },
        xxl: { span: 7 },
      }"
      autocomplete="true"
      layout="horizontal"
    >
      <!-- horizontal vertical inline -->
      <a-card>
        <a-row>
          <a-col span="24">
            <a-form-item label="单据编号" name="data.code" v-bind="validateInfos['data.code']">
              <a-input
                v-model:value="insideData.data.code"
                :size="size"
                disabled
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item
label="出库类型" name="data.ioType"
            :wrapperCol="{
              xs: { span: 15 },
              sm: { span: 12 },
              md: { span: 10 },
              lg: { span: 24 },
              xl: { span: 24 },
              xxl: { span: 24 },
            }"
            >
              <a-radio-group v-if="!isDetail" v-model:value="insideData.data.ioType" :size="size" button-style="solid">
                <a-radio-button v-for="(v, i) in ioTypeList" :key="i" :value="v.ID">{{v.label}}</a-radio-button>
              </a-radio-group>
              <a-button v-else size="large">{{ ioTypeList?.find(e => e.ID === insideData.data.ioType)?.label }}</a-button>
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="订单号" name="data.orderCode">
              <a-input
                v-model:value="insideData.data.orderCode"
                :size="size"
                :disabled="!!isDetail"
                allowClear showCount
                :maxlength="30"
              />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="客户" v-bind="validateInfos['data.customerId']">
              <a-select
                v-model:value="insideData.data.customerId"
                :size="size"
                :disabled="!!isDetail"
                placeholder="请选择"
                :field-names="{label: 'name', value: 'ID',}"
                :options="customerList"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-col span="24">
          <a-form-item
            label="单据备注"
            name="memo"
            :wrapper-col="{ span: 12}"
          >
            <a-textarea
              v-model:value="insideData.data.memo"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              showCount
              :disabled="!!isDetail"
              :maxlength="100"
              placeholder="备注一下..."
            />
          </a-form-item>
        </a-col>
        <!-- <a-divider/> -->
        <!-- 物流信息 -->
        <div style="margin: 0 auto;width: clamp(400px, 100%, 100%);">
          <LogisticsOfEditList ref="logisticsListRef" :is-detail="!!isDetail" :data-list="insideData.data.logisticsList" />
        </div>
        <div style="margin: 0 auto;width: clamp(400px, 100%, 100%);">
          <GoodsOfEditList ref="goodsListRef" :is-detail="!!isDetail" :data-list="insideData.data.goodsList" />
        </div>
        <span style="display: flex; justify-content: center; margin: 2rem 0 8px 0">
        <a-space size="large">
          <a-button size="large" type="default" shape="round" @click="gotoListPage">
            <template #icon><ArrowLeftOutlined/></template>
            返回
          </a-button>
          <a-button v-if="!isDetail" size="large" type="primary" shape="round" @click="onSubmit">
            <template #icon><CheckOutlined/></template>
            提交出库
          </a-button>
          <a-button v-else size="large" type="primary" shape="round" @click="handlePrint">
            <template #icon><PrinterOutlined/></template>
            打印
          </a-button>
        </a-space>
        <!-- <VxeButton
          status="default"
          icon="vxe-icon-close"
          content="关闭页面"
          @click="closeCurrent"
        /> -->
      </span>
      </a-card>
    </a-form>
  </PageWrapper>
</template>
<script lang="ts" name="TabOfOutbound" setup>
// import { Card, Col, DatePicker, Form, FormItem, Row } from 'ant-design-vue';
import { ArrowLeftOutlined, CheckOutlined, PrinterOutlined } from "@ant-design/icons-vue";
import { Form } from 'ant-design-vue';
import 'dayjs/locale/zh-cn';
import { reactive, ref, watchPostEffect } from 'vue';
import { useRoute } from 'vue-router';
import GoodsOfEditList from './GoodsOfEditList.vue';
import LogisticsOfEditList from './LogisticsOfEditList.vue';
import { printStyle, wrap } from "./data";
import { DictItem, getListByMark } from "/@/api/admin/dict";
import { create, getByCode, update } from "/@/api/wms/bill-outbound";
import { CustomerItem, getListData as getCustomerListData } from "/@/api/wms/customer";
import { PageWrapper } from '/@/components/Page';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGo } from '/@/hooks/web/usePage';
import { useTabs } from '/@/hooks/web/useTabs';
import { useUserStore } from '/@/store/modules/user';
import { getCode } from "/@/utils/my";
  const userStore = useUserStore();

  const route = useRoute();
  const { setTitle, closeCurrent } = useTabs();
  const { code, isDetail, history } = route.params;
  if (code) {
    setTitle('编辑 - 出库单');
  } else {
    setTitle('创建 - 出库单');
  }
  if (isDetail) {
    setTitle('出库单详情');
  }

  const go = useGo();
  const gotoListPage = () => {
    closeCurrent().then(() => {
      if (history) {
        go('/history/history')
        return
      }
      go('/warehouse-business/outbound')
    })
  };

  const size = ref('large');
  const useForm = Form.useForm;
  const insideData = reactive({
    data: {
      ID: null,
      code: (!code && !isDetail) ? getCode('CK') : '',
      ioStatus: 1,
      ioType: 14,
      workAt: null,
      supplierId: null,
      customerId: null,
      uid: userStore.getUserInfo.ID,
      orderCode: '',
      memo: '',
      goodsList: [],
      logisticsList: [],
    },
  });

  const rulesRef = reactive({
    'data.code': [{ required: true, message: '编码不能为空' }],
    'data.customerId': [{ required: true, message: '客户不能为空' }],
  });

  // const DateFormat = 'YYYY-MM-DD HH:mm:ss';
  // const workAtRef = ref<Dayjs>();
  // const onValidDateChange = (date: Dayjs | string, dateString: string) => {
  //   insideData.data.workAt = dateString as any;
  // };

  const customerList = ref<CustomerItem[]>()
  const ioTypeList = ref<DictItem[]>()
  watchPostEffect(async () => {
    if (code) {
      getByCode({ code: code }).then((dd) => {
        insideData.data = {...dd}
      });
    }
    getCustomerListData().then(dd => {
      customerList.value = dd.map(e => {
        return { ...e, disabled: e.enable == 2}
      })
    })
    getListByMark({mark: 'bill-outbound-type'}).then(dd => {
      ioTypeList.value = dd.filter(e => e.tag === 0)
    })
  });

  const { resetFields, validate, validateInfos } = useForm(insideData, rulesRef, {
    onValidate: (...args) => {},
  });

  const goodsListRef = ref();
  const logisticsListRef = ref();
  const onSubmit = () => {
    validate()
      .then(async () => {
        let logistics = await logisticsListRef.value.getList()
        let goods = await goodsListRef.value.getGoodsList();
        let { notification } = useMessage();
        if (!goods) {
          return;
        }
        if (goods && goods.length === 0) {
          notification.warning({
            message: '抱歉',
            duration: 6,
            description: '缺少货物，请添加货物！',
          });
          return;
        }

        let reqData = {
          bill: Object.assign({}, insideData.data),
          goodsList: goods,
          logisticsList: logistics,
        };
        if (code && insideData.data.ID) {
          await update(reqData);
        } else {
          await create(reqData);
        }
        closeCurrent().then(() => {
          gotoListPage();
        });
      })
  };
  const handlePrint = () => {
    const $table = goodsListRef.value.getTable()
    if ($table) {
      $table.print({
        sheetName: '打印',
        isHeader: true,
        isFooter: true,
        style: printStyle,
        modes: 'all',
        columns: [
          { field: 'name', title: '货物', minWidth: 150, sortable: false,},
          { field: 'code', title: '货物编号', minWidth: 120, sortable: false,},
          { field: 'cate.name', title: '货物类别', minWidth: 120, sortable: false,},
          { field: 'unit', title: '单位', width: 55, visible: true, sortable: false,},
          // { field: 'barcode', title: '条码', minWidth: 120, visible: false, sortable: false,},
          { field: 'wid', title: '收货仓库/库区', minWidth: 150, visible: true, sortable: false, align: 'left', },
          { field: 'qty', title: '出库数量', minWidth: 80, visible: true, sortable: false, align: 'left',},
          // { field: 'price', title: '单价', minWidth: 100, visible: true, sortable: false, align: 'left',},
          // { field: 'amount', title: '金额', minWidth: 120, visible: true, sortable: true, align: 'left', formatter: 'amount',},
          // { field: 'isGift', title: '赠品', width: 60, align: 'left', visible: true, slots: { default: 'isGift_edit',},},
          // { field: 'memo', title: '备注', minWidth: 120, visible: true, sortable: false,}
        ],
        // data: insideData.data.goodsList,
        beforePrintMethod: ({ content }) => {
          // $table.updateFooter()
          let row = insideData.data as any
          return wrap(row).topHtml + content + wrap(row).bottomHtml
        }
      })
    }
  }
</script>
<style scoped>
  :deep().mytable-style .vxe-body--row.row-enable {
    opacity: 0.62;
  }
  :deep().vben-page-wrapper-content {
    margin-bottom: 8px;
  }
  :deep(.vben-page-footer__right) {
    width: 100%;
  }
  /* :deep().ant-card-body{ width: 70%;min-width: 798px;margin: 0 auto; } */
</style>